document.addEventListener('DOMContentLoaded', function() {
  const searchInput = document.getElementById('search');
  const resultsList = document.getElementById('results');
  let selectedIndex = -1;

  // 自动聚焦到搜索框
  searchInput.focus();

  // 搜索输入事件
  searchInput.addEventListener('input', function () {
    const query = this.value.toLowerCase().trim();
    resultsList.innerHTML = ''; // 清空旧结果
    selectedIndex = -1; // 重置选择

    if (!query) return;

    try {
      if (typeof chrome !== 'undefined' && chrome.bookmarks) {
        chrome.bookmarks.search(query, function (items) {
          if (items.length === 0) {
              resultsList.innerHTML = '<li><a href="#">未找到匹配的书签</a></li>';
              return;
          }
          items.forEach((item, index) => {
            if (item.url) {
              const li = document.createElement('li');
              const a = document.createElement('a');
              a.href = item.url;
              a.textContent = item.title || item.url;
              a.title = `${item.title}\n${item.url}`;
              a.target = "_blank";
              li.appendChild(a);

              // 鼠标悬停时同步选中状态
              li.addEventListener('mouseover', () => {
                selectedIndex = index;
                updateSelection();
              });

              resultsList.appendChild(li);
            }
          });
        });
      } else {
          resultsList.innerHTML = '<li><a href="#">无法访问书签API</a></li>';
      }
    } catch (e) {
        console.error("书签搜索时发生错误:", e);
        resultsList.innerHTML = '<li><a href="#">搜索时出错</a></li>';
    }
  });

  // 键盘导航事件
  searchInput.addEventListener('keydown', function(e) {
    const items = resultsList.getElementsByTagName('li');
    // 如果没有结果或者结果是“未找到”，则不处理键盘事件
    if (items.length === 0 || (items.length === 1 && !items[0].getElementsByTagName('a')[0].href.startsWith('http'))) {
        return;
    }


    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault();
        selectedIndex = (selectedIndex + 1) % items.length;
        updateSelection();
        break;
      case 'ArrowUp':
        e.preventDefault();
        selectedIndex = (selectedIndex - 1 + items.length) % items.length;
        updateSelection();
        break;
      case 'Enter':
        e.preventDefault();
        if (selectedIndex > -1) {
          const selectedItem = items[selectedIndex];
          // 模拟点击链接以在新标签页打开
          selectedItem.getElementsByTagName('a')[0].click();
        }
        break;
    }
  });

  // 更新选中项的视觉效果
  function updateSelection() {
    const items = resultsList.getElementsByTagName('li');
    for (let i = 0; i < items.length; i++) {
      if (i === selectedIndex) {
        items[i].classList.add('selected');
        // 确保选中项在可视区域内
        items[i].scrollIntoView({ block: 'nearest', behavior: 'smooth' });
      } else {
        items[i].classList.remove('selected');
      }
    }
  }
});
